package com.doublefish.doublefishrobot.utils.network;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSONObject;
import com.doublefish.doublefishrobot.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 作者:dugaofeng on 2024/10/17 09:16
 */
public class OKHttpApi {

    private static final String BASE_URL = "https://env-00jxhaanbi2j.dev-hz.cloudbasefunction.cn";

    private static final String GET_APP_INFO_URL = "/api/appinfo";
    private static final String GET_FIRMWARE_URL = "/api/firmware";

    //获取app版本信息
    public static void getAppVersion(Context context, int client, OkHttpCallback callback) {
        if (callback == null) {
            return;
        }
        String url = BASE_URL + GET_APP_INFO_URL;

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("client", client);

        httpClientCall(context, url, jsonObject, callback);
    }

    //获取发球机固件版本信息
    public static void getFirmwareVersion(Context context, int model, OkHttpCallback callback) {
        if (callback == null) {
            return;
        }
        String url = BASE_URL + GET_FIRMWARE_URL;

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("model", model);

        httpClientCall(context, url, jsonObject, callback);
    }


    private static void httpClientCall(Context context, String url, JSONObject jsonObject, OkHttpCallback callback) {
        if (callback == null) {
            return;
        }

        int networkReachability = NetworkReachabilityUtils.networkReachability(context);
        if (networkReachability == 0) {
            //当前没有网络
            callback.onNetworkPermissionError();
            return;
        }

        TokenBean tokenBean = new TokenBean();
        if (tokenBean.getSign() == null || tokenBean.getSign().length() == 0) {
            callback.onCallback(false, context.getString(R.string.token_err));
            return;
        }
        RequestBody requestBody = null;
        if (jsonObject != null) {
            String json = jsonObject.toJSONString();
            requestBody = RequestBody.create(json, MediaType.parse("application/json;charset=utf-8"));
        }

        Request.Builder builder = new Request.Builder()
                .url(url)
                .addHeader("token", tokenBean.getTs())
                .addHeader("sign", tokenBean.getSign());
        if (requestBody != null) {
            builder.post(requestBody);
        }
        Request request = builder.build();

        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onCallback(false, e.getLocalizedMessage());
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                ResponseBody responseBody = response.body();
                if (responseBody == null) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onCallback(false, context.getString(R.string.request_err));
                        }
                    });
                    return;
                }
                String result = responseBody.string();
                // 处理响应结果
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onCallback(response.isSuccessful(), result);
                    }
                });
            }
        });
    }


    public static void downloadFile(Context context,String url, String outPath, OkHttpFileDownloadCallback callback) {
        if (TextUtils.isEmpty(url)) {
            if (callback != null) {
                callback.onDownloadCallback(false, null,context.getString(R.string.download_url_err));
            }
            return;
        }
        int networkReachability = NetworkReachabilityUtils.networkReachability(context);
        if (networkReachability == 0) {
            //当前没有网络
            if (callback != null) {
                callback.onNetworkPermissionError();
            }
            return;
        }

        Request request = new Request.Builder().url(url).build();
        OkHttpClient okHttpClient =  new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                if (callback != null) {
                    callback.onDownloadCallback(false, null,e.getLocalizedMessage());
                }
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    // 处理成功响应的情况，例如将文件保存到本地存储中
//                    String fileName = "文件名"; // 请替换为实际的文件名
                    File outputFile = new File(outPath);
                    if (outputFile.exists()) {
                        outputFile.delete();
                    }
                    InputStream inputStream = response.body().byteStream();
                    OutputStream outputStream = new FileOutputStream(outputFile);
                    byte[] buffer = new byte[2048];
                    int bytesRead;
                    long readSize = 0;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                        readSize += bytesRead;
                        if (callback != null) {
                            callback.onDownloadProgress(readSize);
                        }
                    }
                    outputStream.flush();
                    outputStream.close();
                    inputStream.close();
                    // 执行其他操作，例如更新UI等
                    if (callback != null) {
                        callback.onDownloadCallback(true, outPath, context.getString(R.string.success_download));
                    }
                } else {
                    // 处理错误响应的情况，例如打印错误信息到日志中
                    if (callback != null) {
                        callback.onDownloadCallback(false, null, response.message());
                    }
                }
            }
        });
    }

    public interface OkHttpCallback {
        void onNetworkPermissionError();

        void onCallback(boolean success, String response);
    }


    public interface OkHttpFileDownloadCallback {
        void onNetworkPermissionError();

        void onDownloadProgress(long size);
        void onDownloadCallback(boolean success, String path, String msg);
    }

}
